/*

    This file is part of Hometree.

    Hometree is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Hometree is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Hometree.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2011,2012 Roman Held

*/
#include <QDebug>
#include <QFileDialog>
#include <QDir>
#include <QPixmap>
#include "testwidget.h"

TestWidget::TestWidget()
 : QWidget()
{
  ui.setupUi(this);

  connect(ui.btnConnect1, SIGNAL(clicked()),
          this, SLOT(reconnect()));
  connect(ui.chatInput, SIGNAL(editingFinished()),
          this, SLOT(newChatInput()));
  connect(&mClient, SIGNAL(stateChanged()),
          this, SLOT(clientState()));
  connect(&mResource, SIGNAL(readyRead()),
          this, SLOT(newChatMessage()));
  connect(&mResource, SIGNAL(stateChanged()),
          this, SLOT(resStateChanged()));

  mResource.init(&mClient,ui.url->text());
  mResource.open(Htr::Res::ReadWrite | Htr::Res::Create);

  clientState();
}

void TestWidget::reconnect()
{
  mClient.close();
  QString host = ui.edtHost1->text();
  int port = ui.spnPort1->value();

  if (host.length() > 0 && port > 0) {
    mClient.connectToHost(host,port);
  }
}

void TestWidget::clientState()
{
  ui.chkReady1->setCheckState(mClient.isReady() ? Qt::Checked:Qt::Unchecked);
  ui.resourceWidget->setEnabled(mClient.isReady() ? true:false);
  if (mClient.isReady())
    ui.chatText->setText("");
}

void TestWidget::resStateChanged()
{
  ui.boxState->setCurrentIndex(mResource.state());
  ui.resourceWidget->setEnabled(mResource.state() == Htr::Res::StReady);
  if ((mResource.state() == Htr::Res::StReady) && (mResource.mimeType() != ui.mimeType->text()))
    mResource.setMimeType(ui.mimeType->text());
}

void TestWidget::newChatInput()
{
  QString in = ui.chatInput->text().trimmed();
  if (in.length() > 0)
    mResource.setMimeData(in.toAscii());
  ui.chatInput->setText("");
}

void TestWidget::newChatMessage()
{
  ui.chatText->append(mResource.mimeData());
}

